# -*- coding: utf-8 -*-
from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from customer_information import customer_router
from conversation_log import conversation_router
from websocket_module import websocket_router

app = FastAPI()

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有源，或者指定具体的源，如["https://example.com"]
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有HTTP方法，或者指定具体的方法，如["GET", "POST"]
    allow_headers=["*"],  # 允许所有HTTP头部，或者指定具体的头部
)


# 全局异常处理
@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    return JSONResponse(
        status_code=exc.status_code,
        content={"code": exc.status_code, "message": exc.detail},
    )

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return JSONResponse(
        status_code=422,
        content={"code": 422, "message": "Validation Error", "errors": exc.errors()},
    )

# 引入客户相关的路由
app.include_router(customer_router, prefix="/customers", tags=["customers"])

# 确保路由正确包含（已存在，但需确认无拼写错误）
app.include_router(conversation_router, prefix="/conversation", tags=["conversation"])

app.include_router(websocket_router, prefix="/websocketclient", tags=["websocket"])
